<template>
  <div class="main-page">
    <div class="main-01">
      <div class="main-tab-01-01">
        <div class="main-tab-title">
          <span>评价统计</span>
        </div>
        <div class="table-line-box">
          <div class="table-line-tab">
            <div class="table-line-tab-list" :class="{'active': activeIndex === '1'}" @click="handleSelect('1')">
              今日
            </div>
            <div class="table-line-tab-list" :class="{'active': activeIndex === '2'}" @click="handleSelect('2')">
              本周
            </div>
            <div class="table-line-tab-list" :class="{'active': activeIndex === '3'}" @click="handleSelect('3')">
              本期
            </div>
          </div>
          <div class="table-line-content">
            <div class="table-line-content-header">
              <div class="table-line-content-header-l">
                班级
              </div>
              <div class="table-line-content-header-l">
                人数
              </div>
            </div>
            <div class="table-line-content-box">
              <div class="table-line-content-l" v-for="cls in EvaluationData" :key="cls.id">
                <div class="table-line-content-list">
                  {{ cls.class_name }}
                </div>
                <div class="table-line-content-list">
                  {{ cls.signed_students_count }}人
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="main-tab-01-01">
        <div class="main-tab-title">
          <span>采集统计</span>
        </div>
        <div class="table-line-box">
          <div class="table-line-tab">
            <div class="table-line-tab-list" :class="{'active': uploadIndex === '1'}" @click="handleUploadSelect('1')">
              今日
            </div>
            <div class="table-line-tab-list" :class="{'active': uploadIndex === '2'}" @click="handleUploadSelect('2')">
              本周
            </div>
            <div class="table-line-tab-list" :class="{'active': uploadIndex === '3'}" @click="handleUploadSelect('3')">
              本期
            </div>
          </div>
          <div class="table-line-content">
            <div class="table-line-content-header">
              <div class="table-line-content-header-l">
                班级
              </div>
              <div class="table-line-content-header-l">
                人数
              </div>
            </div>
            <div class="table-line-content-box">
              <div class="table-line-content-l" v-for="cls in UploadData" :key="cls.id">
                <div class="table-line-content-list">
                  {{ cls.class_name}}
                </div>
                <div class="table-line-content-list">
                  {{ cls.uploaded_students_count}}人
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="main-02">
      <div class="main-02-top">
        <div class="main-tab-title" style="margin-bottom: 0">
          <span>周跟踪</span>
        </div>
        <div class="table-line-tab">
          <select v-model="classId" @change="changClassSel($event)" placeholder="班级">
            <option value="" disabled selected style="color: white;">请选择</option>
            <option v-for="item in classList" :value="item.id" :key="item.id">{{ item.class_name }}</option>
          </select>
        </div>
        <div class="dropdown-container" v-loading="loading"
             element-loading-text="加载中"
             element-loading-spinner="el-icon-loading"
             element-loading-background="rgba(0, 0, 0, 0.5)">
          <div class="dropdown-container-in" v-if="cornersData.length">
            <div v-for="student in cornersData" :key="student.id" class="chart-container-line">
              <div :id="`pieChart-${student.id}`" :style="{ width: '315px', height: '315px' }"></div>
            </div>
          </div>
        </div>
      </div>

    </div>
    <div class="main-03">
      <div class="main-tab-01-01">
        <div class="main-tab-title">
          <span> 观察记录（区角）</span>
        </div>
        <div class="box-line-b">
          <div class="table-line-tab">
            <div class="table-line-tab-list">
              <select v-model="classWatchId" @change="changClassWatchSel($event)" placeholder="班级">
                <option value="" disabled selected style="color: white;">请选择</option>
                <option v-for="item in classList" :value="item.id" :key="item.id">{{ item.class_name }}</option>
              </select>
            </div>
            <div class="table-line-tab-list">
              <select v-model="cornerWatchId" @change="changCornerSel($event)" placeholder="区角">
                <option value="" disabled selected style="color: white;">请选择</option>
                <option v-for="item in cornerWatchList" :value="item.id" :key="item.id">{{ item.name }}</option>
              </select>
            </div>
          </div>
          <div class="box-line-b-n">
            <div class="box-line-b-n-list" v-for="(item,index) in watchCornerData" @click="showModal(item)">
              {{ item.name}}
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="main-04">
      <div class="main-tab-01-01">
        <div class="main-tab-title">
          <span>观察记录（幼儿）</span>
        </div>
        <div class="box-line-b">
          <div class="table-line-tab">
            <div class="table-line-tab-list">
              <select v-model="classStudentId" @change="changClassStudentSel($event)" placeholder="班级">
                <option value="" disabled selected style="color: white;">请选择</option>
                <option v-for="item in classList" :value="item.id" :key="item.id">{{ item.class_name }}</option>
              </select>
            </div>
            <div class="table-line-tab-list">
              <select v-model="studentId" @change="changStudentSel($event)" placeholder="学生">
                <option value="" disabled selected style="color: white;">请选择</option>
                <option v-for="item in watchStudentData" :value="item.id" :key="item.id">{{ item.name }}</option>
              </select>
            </div>
          </div>
        </div>
        <!-- 学生名字展示区域 -->
        <div class="student-container" ref="studentContainer">
          <div
            v-for="(student, index) in watchStudentData"
            :key="student.id"
            class="student-name"
            :style="{ top: getRandomPosition().top + 'px', left: getRandomPosition().left + 'px' }"
            @click="handleStudentClick(student)"
          >
            {{ student.name }}
          </div>
        </div>
      </div>
    </div>
    <cornerStudentPoint :visible.sync="cornerPointVisible" :studentName="studentName"
                        :studentId="checkStudentId"></cornerStudentPoint>
    <CornerScoreModal
      :visible.sync="modalVisible"
      :normalizedData="normalizedData"
    ></CornerScoreModal>
  </div>
</template>


<script>
import {
  corner_score_distribution,
  getEvaluationStatistics,
  getTopThreeCornerApplicationsByPosition,
  getUploadStatistics,
  nurseryDashboard, watch_corner, watch_student, weekly_tracking
} from "@/api/admin/school";

let echarts = require('echarts');
import developmentTable from "@/fullscreen/components/developmentTable";
import api from "@/utils/api";
import cornerStudentPoint from "@/views/admin/Corner/components/cornerStudentPoint.vue";
import checkData from "@/views/admin/school/components/checkData";
import CornerScoreModal from '@/views/admin/Corner/components/CornerScoreModal.vue';

export default {
  name: "balancedTracking",
  components: {cornerStudentPoint, developmentTable, CornerScoreModal},
  data() {
    return {
      loading: false,
      modalVisible: false,
      EvaluationData: [],
      UploadData: [],
      activeIndex: "1",
      uploadIndex: "1",
      cornerId: 0,
      cornerName: '',
      classList: [],
      selectList: [],
      cornerWatchList: [],
      studentName: '',
      checkStudentId: 0,
      classId: '',
      classWatchId: '',
      cornerWatchId: '',
      classStudentId: '',
      watchCornerData:[],
      watchStudentData:[],
      selectId: '',
      studentId: '',
      cornersData: {},
      cornerPointVisible: false,
      normalizedData: [],
    }
  },
  computed: {
    checkData() {
      return checkData
    }
  },
  created() {
    this.getSchoolFn();
    this.classWatchInitFn();
    this.cornerInitFn();
  },
  mounted() {

  },
  methods: {
    handleSelect(index) {
      this.activeIndex = index;
      switch (index) {
        case '1':
          this.getEvaluationStatistics("today");
          break;
        case '2':
          this.getEvaluationStatistics("week");
          break;
        case '3':
          this.getEvaluationStatistics("semester");
          break;
        default:
          [];
      }
    },
    handleUploadSelect(index) {
      this.uploadIndex = index;
      switch (index) {
        case '1':
          this.getUploadStatistics("today");
          break;
        case '2':
          this.getUploadStatistics("week");
          break;
        case '3':
          this.getUploadStatistics("semester");
          break;
        default:
          [];
      }
    },
    getEvaluationStatistics(type) {
      getEvaluationStatistics({'dateRange': type}).then(res => {
        if (res.code == 0) {
          this.EvaluationData = res.student;
        }
      })
    },
    getUploadStatistics(type) {
      getUploadStatistics({'dateRange': type}).then(res => {
        if (res.code == 0) {
          this.UploadData = res.student;
        }
      })
    },
    getTopThreeCornerApplicationsByPosition() {
      getTopThreeCornerApplicationsByPosition().then(res => {
        if (res.code == 0) {
          const chartContainer = document.getElementById('morning_Chart');
          const myChart = echarts.init(chartContainer);
          const option = {
            tooltip: {
              trigger: 'axis'
            },
            grid: {
              height: '50%',
              top: '10%'
            },
            xAxis: {
              type: 'category',
              data: res.list.map(item => item.name),
              name: '区角'
            },
            yAxis: {
              type: 'value',
              name: '人数'
            },
            series: [{
              name: '人数',
              type: 'bar',
              data: res.list.map(item => parseInt(item.apply_number)),
              label: {
                show: true
              },
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }]
          };
          option && myChart.setOption(option);
        }
      })
    },
    weekly_tracking() {
      console.log('class_id', this.classId)
      weekly_tracking({'class_id': this.classId}).then(res => {
        if (res.code == 0) {
          console.log('res', res.data.corners)
          this.cornersData = res.data.corners
          setTimeout(() => {
            for (let index in res.data.corners) {
              let character = res.data.corners[index]
              if (character && character.id) {
                this.initPieChart(character, index);
              } else {
                console.error('Invalid character data:', character);
              }
            }
          }, 300)
        }
      })
    },
    watch_corner(){
      watch_corner({'class_id': this.classWatchId,'corner_id': this.cornerWatchId}).then(res => {
        if (res.code == 0) {
          this.watchCornerData = res.data
        }
      })
    },
    watch_student(){
      watch_student({'class_id': this.classStudentId,'student_id': this.studentId}).then(res => {
        if (res.code == 0) {
          this.watchStudentData = res.data
        }
        console.log('watchStudentData:', this.watchStudentData)
      })
    },
    initPieChart(character, index) {
      console.log('Character:', character); // 打印 character 对象

      console.log(`Initializing pie chart for character: ${character.id}`); // 调试信息
      const chartId = `pieChart-${character.id}`;
      const chartContainer = document.getElementById(chartId);
      if (!chartContainer) {
        console.error(`Element with id "${chartId}" not found`);
        return;
      }

      const chart = echarts.init(chartContainer);

      // 提取已预约和未预约学生信息
      const bookedCount = character.booked_students_info.length;
      const notBookedCount = character.not_booked_students_info.length;
      const totalCount = bookedCount + notBookedCount;
      const bookedPercentage = ((bookedCount / totalCount) * 100).toFixed(2);
      const notBookedPercentage = ((notBookedCount / totalCount) * 100).toFixed(2);

      const data = [
        {
          name: "已参与",
          value: parseFloat(bookedPercentage),
          booked_students_info: character.booked_students_info
        },
        {
          name: "未参与",
          value: parseFloat(notBookedPercentage),
          not_booked_students_info: character.not_booked_students_info
        }
      ];

      const option = {
        title: {
          text: `${character.name}`,
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: (params) => {
            let tooltipContent = `${params.seriesName}<br/>${params.marker}${params.name}: ${params.percent}%<br/>`;

            if (params.data.booked_students_info && Array.isArray(params.data.booked_students_info)) {
              tooltipContent += '已到:<br/>';
              params.data.booked_students_info.forEach(student => {
                tooltipContent += `- ${student.name} <br/>`;
              });
            }

            if (params.data.not_booked_students_info && Array.isArray(params.data.not_booked_students_info)) {
              tooltipContent += '未到:<br/>';
              params.data.not_booked_students_info.forEach(student => {
                tooltipContent += `- ${student.name} <br/>`;
              });
            }

            return tooltipContent;
          }
        },
        series: [
          {
            name: '学生签到情况',
            type: 'pie',
            radius: '50%',
            center: ['50%', '60%'],
            data: data,
            label: {
              show: true,
              formatter: '{b}: {c} ({d}%)'
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ],
        backgroundColor: '#fff'
      };

      chart.setOption(option);
      if (this.cornersData.length - 1 == index) {
        setTimeout(() => {
          this.loading = false;
        }, 400);
      }
    },
    changCornerSel(event) {
      this.cornerWatchId = event.target.value
      this.watch_corner();
    },
    changStudentSel(event) {
      this.studentId = event.target.value
      this.watch_student();
    },
    changClassSel(event) {
      this.classId = event.target.value
      this.weekly_tracking();
    },
    changClassWatchSel(event) {
      this.classWatchId = event.target.value
      this.watch_corner();
      this.$fetch(api.admin_corner_index, {
        p: 1,
        class_id: this.classWatchId
      }).then((response) => {
        console.log('cornerInitFn', response);
        this.cornerWatchList = this.watchCornerData = response.list.data;
      }).catch((err) => {
        console.log(err);
      });
    },
    changClassStudentSel(event) {
      this.classStudentId = event.target.value
      this.studentId = ''
      this.watch_student();
    },
    classWatchInitFn() {
      this.$fetch(api.admin_classes_index, {
        p: 1,
        is_classroom:1
      }).then((response) => {
        this.classList = response.list.data;
        // 设置默认选中的班级
        if (this.classList.length > 0) {
          this.classWatchId = this.classId = this.classStudentId = this.classList[0].id;
          this.watch_corner();
          this.weekly_tracking();
          this.watch_student();
        }
      }).catch((err) => {
        console.log(err);
      });
    },
    cornerInitFn() {
      this.$fetch(api.admin_corner_index, {
        p: 1
      }).then((response) => {
        console.log('cornerInitFn', response);
        this.cornerWatchList = response.list.data;

      }).catch((err) => {
        console.log(err);
      });
    },
    getRandomPosition() {
      const container = this.$refs.studentContainer;
      const top = Math.floor(Math.random() * (container.clientHeight - 60)); // 减去一些偏移量防止超出边界
      const left = Math.floor(Math.random() * (container.clientWidth - 120)); // 减去一些偏移量防止超出边界
      return { top, left };
    },
    handleStudentClick(student) {
        this.studentName = student.name
        this.studentId = student.id
        this.cornerPointVisible = true
    },
    corner_score_distribution(corner_id) {
      return corner_score_distribution({'class_id': this.classWatchId, "corner_id": corner_id}).then(res => {
        console.log('归一化的数据:', res);
        return res; // 返回数据以便在 showModal 中使用
      });
    },

    async showModal(item) {
      const normalizedData = await this.corner_score_distribution(item.id);
      this.studentName = item.name;
      this.checkStudentId = item.id;
      this.normalizedData = normalizedData; // 存储归一化的数据
      this.modalVisible = true;
    },
    handleCloseModal() {
      this.modalVisible = false;
    },
    getSchoolFn() {
      this.handleSelect(this.activeIndex);
      this.handleUploadSelect(this.uploadIndex);
      this.getTopThreeCornerApplicationsByPosition();
    }
  }
}
</script>

<style scoped>
.main-page {
  display: flex;
  padding: 10px;
}

.main-tab-title {
  background: url(./assets/img/h-008.png) no-repeat;
  background-size: 100% 50px;
  background-position: left bottom;
  height: 50px;
  font-style: italic;
  font-size: 26px;
  padding-left: 40px;
  line-height: 24px;
  font-weight: 500;
  margin-bottom: 10px;
}

.main-tab-title span {
  background: linear-gradient(to bottom, #fff, #fcfcb8);
  -webkit-background-clip: text; /* 将背景裁剪为文字区域 */
  -webkit-text-fill-color: transparent; /* 将文字颜色设置为透明 */
  /*color: #fcfcb8;*/
  /*text-shadow: 2px 2px 1px #000;*/
}

.main-content {
  font-size: 18px;
  color: #fff;
}

.main-01 {
  width: 20%;
  background: rgba(5, 25, 53, .6);
  border-radius: 10px;
  padding: 10px;
  display: flex;
  flex-direction: column;
}

.main-02 {
  flex: 1;
  background: rgba(5, 25, 53, .6);
  border-radius: 10px;
  height: 1680px; /* 设置固定高度 */
  overflow-y: auto; /* 启用垂直滚动条 */
  border: 1px solid #ccc; /* 可选：添加边框以便更明显 */
}

.main-03 {
  width: 20%;
  background: rgba(5, 25, 53, .6);
  border-radius: 10px;
  padding: 10px;
  margin-right: 20px;
}

.main-04 {
  width: 20%;
  background: rgba(5, 25, 53, .6);
  border-radius: 10px;
  padding: 10px;
}

.main-tab-box-t-01 span:nth-child(1) {
  font-size: 14px;
  color: #ddd;
  margin-bottom: 5px;
  display: block;
}

.main-tab-box-t-01 span:nth-child(2) {
  font-size: 20px;
}

.main-tab-01-01 {
  flex: 1; /* 使每个子元素高度相等 */
  display: flex;
  flex-direction: column;
  margin-bottom: 30px;
}

.dropdown-container {
  flex: 1;
  overflow: hidden;
}

.dropdown-container-box {
  padding: 10px 0 20px;
  font-size: 24px;
  color: #fff;
  display: flex;
  align-items: center;
  /*height: 50px;*/
}

.dropdown-container-in {
  padding: 10px;
  overflow-y: auto;
  height: 100%;
}

.dropdown-container-box select {
  width: 180px;
  height: 50px;
  font-size: 24px;
  /*background: rgba(5, 25, 53, .6);*/
  color: #000;
  border: 1px solid #ddd;
  padding: 5px;
  border-radius: 5px;
  appearance: none;
  -webkit-appearance: none;
  -moz-appearance: none;
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24"><path fill="%23ddd" d="M7 10l5 5 5-5z"/></svg>');
  background-repeat: no-repeat;
  background-position: right 10px center;
  background-size: 12px;
  margin-right: 10px;
}

.dropdown-container-box input {
  width: 150px;
  height: 50px;
  font-size: 24px;
  border-radius: 5px;
  padding-left: 10px;
}

.dropdown-container-box select:focus {
  outline: none;
}

.dropdown-btn {
  margin-left: 20px;
  border: 1px solid #fff;
  line-height: 48px;
  height: 50px;
  width: 120px;
  text-align: center;
  border-radius: 10px;
  cursor: pointer;
}

.dropdown-btn:hover {
  background: rgba(255, 255, 255, .4);
}

.attendance-table {
  width: 100%;
  border-collapse: collapse;
}

.attendance-table th,
.attendance-table td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: center; /* 居中对齐 */
  color: white; /* 字体颜色为白色 */
}

.attendance-table th {
  background-color: #333; /* 表头背景颜色 */
}

.attendance-table td {
  color: #52ffff;
}


.comment-item p {
  margin: 0;
  font-size: 16px;
  height: 36px;
  color: #fff;
}

.comment-item p strong {
  margin: 20px;

}

.banner-box img {
  width: 100%;
  display: block;
}

.line-01-bottom p {
  display: flex;
  align-items: center;
  margin-top: 10px;
}

.line-01-bottom p span {
  display: block;
}

.line-01-bottom p span:first-child {
  width: 100px;
}

.line-02-bottom p {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.line-02-bottom p span {
  display: block;
}

.line-02-bottom p span:first-child {
  width: 160px;
}

.student-container {
  position: relative;
  width: 100%;
  height: 960px; /* 增加高度 */
  margin-top: 20px;
}

.student-name {
  position: absolute;
  cursor: pointer;
  color: white; /* 文字颜色 */
  font-size: 20px; /* 增大字体大小 */
  background: radial-gradient(circle, rgba(255, 255, 0, 0.8), rgba(255, 255, 0, 0)); /* 径向渐变背景 */
  padding: 10px 20px; /* 调整内边距 */
  border-radius: 50%; /* 圆形背景 */
  width: 100px; /* 设置宽度 */
  height: 100px; /* 设置高度 */
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); /* 添加阴影效果 */
}
.main-page {
  overflow-x: hidden;
}

.main-02-top {
  padding: 10px;
}

.chart-container-line {
  float: left;
  width: 317px;
  margin-bottom: 10px;
}

.chart-container-line:nth-child(2n-1) {
  margin-right: 10px;
}

.table-line-tab {
  display: flex;
  justify-content: space-around;
  margin-bottom: 10px;
}

.table-line-tab-list {
  padding: 0 20px;
  height: 30px;
  line-height: 30px;
  color: #fff;
}

.table-line-tab-list.active {
  background-image: linear-gradient(to right, rgba(134, 206, 255, .1), rgba(1, 174, 239, .4), rgba(134, 206, 255, .1));
}
.table-line-content-header{
  height: 30px;
  line-height: 30px;
  color: #fff;
  display: flex;
  align-items: center;
}
.table-line-content-header-l{
  padding: 0 10px;
  box-sizing: border-box;
  flex: 1;
  background: rgba(255,255,255,.2);
}
.table-line-content-header-l:first-child{
  margin-right: 2px;
}
.table-line-content-l{
  display: flex;
  align-items: center;
}
.table-line-content-l:nth-child(2n) .table-line-content-list{
  background: rgba(64, 86, 124,.4);
}
.table-line-content-list{
  flex: 1;
  color: #fff;
  height: 30px;
  line-height: 30px;
  padding: 0 10px;
}
.table-line-content-list:first-child{
  margin-right: 2px;
}
.box-line-b-n-list{
  width: 70%;
  height: 100px;
  text-align: center;
  line-height: 100px;
  background: rgba(0,12,36,.4);
  margin: 0 auto 10px;
  color: #fff;
  box-shadow: inset 0 0 8px 8px #06375e;
  font-size: 18px;
}
</style>
